﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace UBlockly.Compotent
{
    /// <summary>
    /// 侧栏
    /// </summary>
    [SerializeField]
    public class USideBarHandler : MonoBehaviour,ISideBarHandler
    {
        bool isInit = false;
        Dictionary<int, GameObject> folderMap;
        [SerializeField] int upDownOffset = 20;
        [SerializeField] int leftOffset = 20;
        [SerializeField] int blockSpace = 30;
        [SerializeField] RectTransform leftBarTransform;
        [SerializeField] Transform gridTransform;
        [SerializeField] GameObject classiflyItem;
        [SerializeField] RectTransform folderPanel;
        [SerializeField] ScrollRect folderScroll;
        public RectTransform rectTransform => leftBarTransform;

        //初始化分类信息
        public void InitClassifly(ClassiflyItem[] tags)
        {
            if (isInit || tags == null)
            {
                Debug.LogError("侧栏分类为空");
                return;
            }
            isInit = true;
            folderMap = new Dictionary<int, GameObject>(tags.Length);
            for (int i = 0; i < tags.Length; i++)
            {
                var go = GameObject.Instantiate(classiflyItem, gridTransform);
                go.transform.localScale = Vector3.one;
                var icon = go.GetComponentInChildren<UnityEngine.UI.Image>();
                icon.sprite = Sprite.Create(tags[i].Icon, icon.rectTransform.rect, Vector2.one * 0.5f);
                go.GetComponentInChildren<UnityEngine.UI.Text>().text = tags[i].Name;
                int k = i;
                go.AddCompontentIfNoExist<UnityEngine.UI.Button>().onClick.AddListener(() => { OnClassiflyClick(k); });

                var p = CreateFolderPanel(i);
                folderMap.Add(i, p.gameObject);
            }
        }
        //点击打开对应分类
        void OnClassiflyClick(int classifly)
        {
            if (classifly == GetOpenedFloder())
            {
                CloseOpenedFloder();
            }
            else
            {
                CloseOpenedFloder();
                OpenFloder(classifly);
            }
        }
        //添加到对应分类
        public void AddToLeftBar(int classifly, RectTransform[] trans)
        {
            if (!folderMap.ContainsKey(classifly))
                throw new System.Exception($"没有对应栏目{classifly}");
            var p = folderMap[classifly];
            if (p.transform.childCount != 0)
                return;
            float lastEndYpos = -upDownOffset;
            p.GetComponent<RectTransform>().sizeDelta = new Vector2(folderPanel.sizeDelta.x, GetHeight(trans, blockSpace, upDownOffset));
            for (int i = 0; i < trans.Length; i++)
            {
                trans[i].SetParent(p.transform);
                trans[i].localScale = Vector3.one;
                trans[i].anchoredPosition = new Vector2(leftOffset, lastEndYpos);
                lastEndYpos -= (trans[i].sizeDelta.y + blockSpace);
            }
        }
        //获取打开的分类Id
        public int? GetOpenedFloder()
        {
            foreach (var kvp in folderMap)
            {
                if (kvp.Value.activeSelf)
                    return kvp.Key;
            }
            return null;
        }
        //打开对应的分类
        public void OpenFloder(int classifly)
        {
            GameObject go = null;
            if (folderMap.TryGetValue(classifly, out go))
            {
                go.SetActive(true);
                folderScroll.content = go.GetComponent<RectTransform>();
            }
            folderScroll.gameObject.SetActive(true);
        }
        //关闭打开的分类
        public void CloseOpenedFloder()
        {
            var openedId = GetOpenedFloder();
            if (openedId != null)
            {
                folderMap[(int)openedId].SetActive(false);
            }
            folderScroll.gameObject.SetActive(false);
        }

        RectTransform CreateFolderPanel(int classify)
        {
            var rectt = GameObject.Instantiate(folderPanel, leftBarTransform);
            rectt.SetParent(folderScroll.transform);
            rectt.localScale = Vector3.one;
            rectt.anchoredPosition = folderPanel.anchoredPosition;
            rectt.gameObject.SetActive(false);
            return rectt;
        }

        float GetHeight(RectTransform[] rects,int hSpace,int boardOffset)
        {
            if (rects == null) return 0;
            float height = boardOffset * 2;
            for (int i = 0; i < rects.Length; i++)
            {
                height += rects[i].sizeDelta.y;
            }
            return height += hSpace * (rects.Length - 1);
        }
    }
}
